package light.head.framework.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 简航 E-mail:janhang@126.com 
 * 创建时间：2008-11-21 17:13:54
 */
public class IPUtils {
	
	/**
	 * 配额和获取客户端IP(getClientAddress)方法，验证字符串是否IP地址
	 * @param IP地址字符串
	 * @return 是否IP地址
	 * @author 简航 2008-11-24 09:47:07
	 */
	public static Boolean isIpAddress(String s) {
		String regex = "(((2[0-4]\\d)|(25[0-5]))|(1\\d{2})|([1-9]\\d)|(\\d))[.](((2[0-4]\\d)|(25[0-5]))|(1\\d{2})|([1-9]\\d)|(\\d))[.](((2[0-4]\\d)|(25[0-5]))|(1\\d{2})|([1-9]\\d)|(\\d))[.](((2[0-4]\\d)|(25[0-5]))|(1\\d{2})|([1-9]\\d)|(\\d))";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(s);
		return m.matches();
	}

	/**
	 * 获取客户端IP地址
	 * @param request对象
	 * @return 客户端IP地址
	 * @author 简航 2008-11-24 09:46:19
	 */
	public static String getClientAddress(HttpServletRequest request) {
		String address = request.getHeader("X-Forwarded-For");
		if (address != null && isIpAddress(address)) {
			return address;
		}
		return request.getRemoteAddr();
	}
}
